package com.luli.service.impl;

import com.luli.dao.TreeDao;
import com.luli.entity.tree.CatalogVO;
import com.luli.service.TreeService;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 陆离
 * 2022/7/30 17:28:33
 */
@Service
public class TreeServiceImpl implements TreeService {
    @Autowired
    private TreeDao treeDao;

    @Override
    public List<CatalogVO> getTree() {
        List<CatalogVO> listData = new ArrayList<>();
        List<CatalogVO> tree = treeDao.getTree();
        for (CatalogVO query : tree) {
            if(query.getParentId()==null||"".equals(query.getParentId())){
                continue;
            }
            //父菜单id为0，则为一级菜单
            if("0".equals(query.getParentId())) {
                listData.add(getProcessQueryNodes(query, tree));
            }
        }
        return listData;
    }

    private CatalogVO getProcessQueryNodes(CatalogVO processQuery, List<CatalogVO> processQueries) {
        String id = processQuery.getId();
        if (null == id || StringUtils.isBlank(id)) {
            return null;
        }
        List<CatalogVO> childMenus = new ArrayList<>();
        for (CatalogVO resourceTemp : processQueries) {
            String parentId = resourceTemp.getParentId();
            if (id.equals(parentId)) {
                getProcessQueryNodes(resourceTemp, processQueries);
                childMenus.add(resourceTemp);
            }
        }
        processQuery.setChirldren(childMenus);
        processQuery.checkChild();
        return processQuery;
    }


    @Override
    public List<Map<String, Object>> getTreeMaps() {
        List<Map<String, Object>> listData = new ArrayList<>();
        List<Map<String, Object>> tree = treeDao.getTreeMaps();
        for (Map query : tree) {
            listData.add(getProcessQueryNodes(query, tree));
        }
        return listData;
    }

    private Map getProcessQueryNodes(Map<String, Object> processQuery, List<Map<String, Object>> processQueries) {
        String id = String.valueOf(processQuery.get("id"));
        if (null == id || StringUtils.isBlank(id)) {
            return null;
        }
        List<Map<String, Object>> childMenus = new ArrayList<>();
        for (Map resourceTemp : processQueries) {
            String parentId = String.valueOf(resourceTemp.get("parent_id"));
            if (id.equals(parentId)) {
                getProcessQueryNodes(resourceTemp, processQueries);
                childMenus.add(resourceTemp);
            }
        }
        processQuery.put("childMenus", childMenus);
        return processQuery;
    }
}
